/*
 *  LanguageManager.java
 *
 *  Course Project for User Interface Programming I, 2011
 *  Group 19
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 */
package justdoit.controller;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * This class is for loading Locales from Resources, managing multiple languages
 * (or localization), managing mnemonics of menu items
 * 
 * @author Can
 */
public class LanguageManager {

    private final static String baseName = "justdoit.resources/Locale";
    private static ResourceBundle currentResource = null;

    public static String getString(String key) {
        String keyValue;
        try {
            keyValue = currentResource.getString(key);
        } catch (MissingResourceException mre) {
            System.out.println(mre.getMessage());
            return "NULL";
        } catch (NullPointerException npe) {
            System.out.println(npe.getMessage());
            return "NULL";
        } catch (ClassCastException cce) {
            System.out.println(cce.getMessage());
            return "NULL";
        }
        return keyValue;
    }

    // return -1 if error
    public static int getMnemonic(String key) {
        String mnemonicString = LanguageManager.getString(key);
        if (mnemonicString.equalsIgnoreCase("NULL")) {
            return -1;
        } else {
            return (int)(mnemonicString.charAt(0));
        }
    }

    public static int loadLanguage(Locale newLocale) {
        try {
            currentResource = ResourceBundle.getBundle(
                    baseName + "_" + newLocale.toString());
        } catch (MissingResourceException mre) {
            System.out.println(mre.getMessage());
            return -1;
        }
        return 0;
    }

    public static Locale[] getAvailableLocales() {
        Locale[] langs = new Locale[3];
        langs[0] = new Locale("en", "US");
        langs[1] = new Locale("ru", "RU");
        langs[2] = new Locale("tr", "TR");
        return langs;
    }

    public static void main(String[] args) {
        String[] ISOLanguages = Locale.getISOLanguages();
        System.out.println("ISOLanguages:");
        for (String lang : ISOLanguages) {
            System.out.print(lang + " ");
        }
        System.out.println("\nISOCountries:");
        String[] ISOCountries = Locale.getISOCountries();
        for (String coun : ISOCountries) {
            System.out.print(coun + " ");
        }
        Locale[] allLocale = Locale.getAvailableLocales();
        System.out.println("\nAll Available Locales:");
        for (Locale l : allLocale) {
            System.out.print("" + l.getDisplayLanguage() + " ");
        }
    }
}
